<?php
require_once dirname(__FILE__).'/autoload.php';

$HTTP_PROXY_LIST = file_get_contents(dirname(__FILE__).'/Fast-Proxy.txt');

$arrProxyList = array_unique(array_filter(explode('<br />', nl2br(trim($HTTP_PROXY_LIST)))));
foreach ($arrProxyList as &$proxy) {
    $proxy = preg_replace('#\s+#', '', $proxy);
}unset($proxy);

shuffle($arrProxyList);

$GlobalCountIncr = array();
$GlobalCountIncr['errno'] =array();
$GlobalCountIncr['ok']=array();

function curl_string($url) {
    $intTime = microtime(true);

    global $arrProxyList;
    global $GlobalCountIncr;

    foreach ($arrProxyList as $proxyServer) {
        if (!array_key_exists($proxyServer, $GlobalCountIncr['errno']) && intval($GlobalCountIncr['ok'][$proxyServer]) < 10) {
            $proxy = $proxyServer;
            break;
        }
    }

    $ua = array(
        'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)',
        '(compatible; MSIE 7.01; MSN 2.5; AOL 4.0; Windows XP)',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11',
    );

    log::n('proxy[' . $proxy . '] fetching:' . $url);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_PROXY, $proxy);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_USERAGENT, $ua[mt_rand(0, count($ua) - 1)]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    $result = curl_exec($ch);
    if ($curl_errno = curl_errno($ch)) {
        $GlobalCountIncr['errno'][$proxy] ++;
        log::w('proxy[' . $proxy . '] fetch errno:' . $curl_errno . ',error:' . curl_error($ch));
        return curl_string($url);
    } else {
        $GlobalCountIncr['ok'][$proxy] ++;
        log::n('proxy[' . $proxy . '] fetch success,cost[' . (microtime(true) - $intTime) . ']');
    }
    curl_close($ch);
    return $result;
}

//echo curl_string('http://imail.sinaapp.com/ip.php');

?>